<template>
  <div class="personal-info">
    <div class="header">
      <van-icon name="arrow-left" class="back-icon" @click="goBack"/>
      <h2 style="margin: auto">个人资料</h2>
    </div>
    <div class="content">
      <div class="avatar-section">
        <van-image
            round
            width="100"
            height="100"
            :src="user.avatarUrl"
            @click="handleAvatarClick"
        />
        <van-uploader
            v-model="fileList"
            :after-read="afterRead"
            multiple
            :max-count="1"
            accept="image/*"
            :max-size="2 * 1024 * 1024"
            @oversize="onOversize"
            ref="uploader"
            style="display: none"
        >
        </van-uploader>
      </div>
      <div class="info-section">
        <div class="info-item">
          <span class="label">昵称</span>
          <van-field
              v-model="user.username"
              placeholder="请输入昵称"
          />
        </div>
        <div class="info-item">
          <span class="label">性别</span>
          <van-radio-group v-model="user.sex">
            <van-radio name="1">男</van-radio>
            <van-radio name="2">女</van-radio>
          </van-radio-group>
        </div>
      </div>
      <div class="confirm-button">
        <van-button type="primary" block @click="confirm">确认</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { Button, Field, Icon, Radio, RadioGroup, Toast } from "vant";
import OSS from "ali-oss";
import axios from "axios";

export default {
  components: {
    [Icon.name]: Icon,
    [Field.name]: Field,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Button.name]: Button
  },
  data() {
    return {
      user: {
        sex:"2"
      }, // 确保 user 初始化为一个空对象
      fileList: [],
      avatarUrl: 'https://img.yzcdn.cn/vant/apple-1.jpg',
      client: null // 初始化 client 为 null
    };
  },
  mounted() {
    console.log("oss正在初始化");
    // 初始化 OSS 客户端
    this.initOSSClient()
        .then(() => console.log("oss已经初始化"))
        .catch(err => console.error("oss初始化失败", err));

    const userStr = sessionStorage.getItem("userDB");
    if (userStr) {
      try {
        this.user = JSON.parse(userStr);
        console.log(this.user);
      } catch (error) {
        console.error("解析用户数据失败:", error);
        this.user = {}; // 如果解析失败，重置为一个空对象
      }
    } else {
      console.log("没有找到用户数据");
      this.user = {}; // 如果没有找到用户数据，初始化为一个空对象
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    confirm() {
      // 发送用户数据到后端进行更新
      try {
        // 确保 this.user 是一个对象
        if (typeof this.user !== 'object' || this.user === null) {
          console.error('this.user 不是一个有效的对象', this.user);
          Toast.fail('更新失败');
          return;
        }
        axios.put('http://localhost:10086/api/admin/user/update', JSON.stringify(this.user), {
          headers: {
            'Content-Type': 'application/json'
          }
        })
            .then(response => {
              console.log('用户数据已发送到后端进行更新', response.data);
              Toast.success('更新成功');
              sessionStorage.setItem("userDB", JSON.stringify(this.user));
              // 回退到个人中心
              this.$router.go(-1);
            })
            .catch(error => {
              console.error('发送用户数据到后端失败', error);
              Toast.fail('更新失败');
            });
      } catch (error) {
        console.error('发送用户数据到后端失败', error);
        Toast.fail('更新失败');
      }
    },

    handleAvatarClick() {
      this.$refs.uploader.chooseFile();
    },
    async initOSSClient() {
      try {
        this.client = new OSS({
          region: 'oss-cn-beijing',
          accessKeyId: 'LTAI5tQwt4SyLnr6F2HuyHpt', // 确保这是有效的 Access Key ID
          accessKeySecret: 'iO82QxhjEsjRa4GtdvTfThKdSS8Kbf', // 确保这是有效的 Access Key Secret
          bucket: 'test-demo-cjl'
        });
        console.log("oss已经初始化");
      } catch (err) {
        console.error("oss初始化失败", err);
        Toast.fail('OSS 初始化失败');
      }
    },
    onOversize(file) {
      Toast.fail(`文件大小不能超过 2MB`);
    },
    async afterRead(file) {
      console.log('file:', file); // 打印文件对象
      if (!this.client) {
        console.error('OSS 客户端未初始化');
        Toast.fail('OSS 客户端未初始化');
        return;
      }

      this.fileList = [file];
      try {
        const objectKey = `avatars/${Date.now()}-${file.file.name}`;
        console.log('objectKey:', objectKey); // 打印对象键
        const result = await this.client.put(objectKey, file.file);
        const imageUrl = result.url;
        if (this.user) { // 确保 this.user 存在
          this.user.avatarUrl = imageUrl; // 修改为 avatarUrl
          this.avatarUrl = imageUrl;
          console.log('上传成功:', result);
        } else {
          console.error('this.user 未定义');
          Toast.fail('用户数据未定义');
        }
      } catch (error) {
        console.error('上传头像失败', error);
        console.error('错误详情:', error.message, error.stack);
        Toast.fail('上传头像失败');
      }
    }
  },
};

</script>

<style scoped>
.personal-info {
  display: flex;
  flex-direction: column;
  align-items: center; /* 将内容居中 */
  background-color: white;
  height: 100vh; /* 占满视口高度 */
  justify-content: center; /* 垂直居中 */
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ccc;
  width: 100%; /* 占满父元素宽度 */
}

.back-icon {
  font-size: 20px;
  cursor: pointer;
}

.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.avatar-section {
  margin-bottom: 20px;
}

.info-section {
  width: 100%;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #ccc;
}

.label {
  font-size: 16px;
}

.confirm-button {
  margin-top: 20px;
}
</style>
